package com.itboye.ihomebank;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.itboye.ihomebank.activity.home.ActivitySwitchRoles;
import com.itboye.ihomebank.activity.integral_mall.ActivityExchangeMall;
import com.itboye.ihomebank.activity.integral_mall.ActivityMyIntgral;
import com.itboye.ihomebank.activity.login.LoginActivity;
import com.itboye.ihomebank.activity.me.ActivityMyData;
import com.itboye.ihomebank.activity.me.ActivitySetting;
import com.itboye.ihomebank.activity.myzhujia.ActivityMyWallte;
import com.itboye.ihomebank.activity.myzhujia.qianbao.ActivityZhiFuPassSheZhi;
import com.itboye.ihomebank.base.BaseFragment;
import com.itboye.ihomebank.bean.AgentCenterBean;
import com.itboye.ihomebank.bean.MyWalletBean;
import com.itboye.ihomebank.bean.PersonDataBean;
import com.itboye.ihomebank.bean.ResultEntity;
import com.itboye.ihomebank.constants.NetPublicConstant;
import com.itboye.ihomebank.constants.SPContants;
import com.itboye.ihomebank.custom.LoweLinearLayout;
import com.itboye.ihomebank.presenter.UserPresenter;
import com.itboye.ihomebank.util.ByAlert;
import com.itboye.ihomebank.util.DoubleUtil;
import com.itboye.ihomebank.util.SPUtils;
import com.itboye.ihomebank.util.SavePersonData;
import com.itboye.ihomebank.util.controller.LoginController;
import com.itboye.ihomebank.web.WebActivity;
import com.itboye.ihomebank.widget.rollingtv.NumberRollingView;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreater;
import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreater;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.text.DecimalFormat;
import java.util.Observable;
import java.util.Observer;

/**
 * 我的
 *
 * @author
 */
public class MeFragment extends BaseFragment implements OnClickListener, Observer {
    View v_statusbar;
    LinearLayout person_qiehuan;//房源管理
    ImageView person_shezhi;// 设置
    String uid = "";
    SmartRefreshLayout refresh;
    LinearLayout layout_geren, layout_jingjiren, layout_unlogin;//个人，经纪人，没有登录
    NumberRollingView me_qianyue_num,me_qianyue_num1,me_qianyue_num2,rentNumTv;//签约 空置 房源 累计收租 （数量）
    LoweLinearLayout lin_sign, lin_rental, lin_collection, lin_housekeeper, lin_wallet, lin_detailed,
            card_voucher,exchangeLl;//签约。求租。收藏。管家。钱包。明细。我的卡券。兑换
    NumberRollingView me_money;//个人 余额
    private UserPresenter userPresenter;
    ImageView mySign_img;
    String broker_validate;////经纪人认证【0未认证,1已认证,2待审核】'

    //登录和退出登录的广播
    BroadcastReceiver loginReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            uid = SPUtils.get(getActivity(), null, SPContants.USER_ID, "") + "";
            broker_validate= SPUtils.get(getActivity(),null,SPContants.BrokerValidate,"")+"";
            Log.e("Home----","true");
            if (refresh!=null){
                if(uid.equals("")){
                    refresh.setEnableRefresh(false);
                }else {
                    refresh.setEnableRefresh(true);
                    refresh.autoRefresh();
                }
            }
            titleShow();
            isShowRedDot();

        };
    };
    @Override
    public int initView() {
        return R.layout.activity_person_centre;
    }

    @Override
    public void onMyActivityCreated() {

    }

    @Override
    public void onResume() {
        super.onResume();
        Log.d("====Me","=========");
        uid = SPUtils.get(getActivity(), null, SPContants.USER_ID, "") + "";
        isShowRedDot();
        if (SPUtils.get(getActivity(),null,SPContants.BrokerValidate,"").equals("0")
                ||SPUtils.get(getActivity(),null,SPContants.BrokerValidate,"").equals("2")){//租客
            Log.d("====Me","====myWallet=====");
            userPresenter.myWallet(uid);
        }else if (SPUtils.get(getActivity(),null,SPContants.BrokerValidate,"").equals("1")){//经纪人
            userPresenter.agentCenter(uid);
            Log.d("====Me","====agentCenter=====");
        }

//        updateRedDot(mySign_img, (Boolean) SPUtils.get(getActivity(),null,SPContants.FUJIAN_ORDER,false));
    }
     //刷新操作
    private void caozuo(){

//        refresh.setEnableAutoLoadmore(true);//开启自动加载功能（非必须）
        if(uid.equals("")){
            refresh.setEnableRefresh(false);
        }else {
            refresh.setEnableRefresh(true);
            refresh.autoRefresh();
        }

        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                refreshlayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                if (SPUtils.get(getActivity(),null,SPContants.BrokerValidate,"").equals("0")
                        ||SPUtils.get(getActivity(),null,SPContants.BrokerValidate,"").equals("2")){//租客

                    userPresenter.myWallet(uid);
                }else if (SPUtils.get(getActivity(),null,SPContants.BrokerValidate,"").equals("1")){//经纪人
                    userPresenter.agentCenter(uid);
                }
                    }
                }, 0);
            }
        });

//        //进行加载更多的逻辑处理
//        refresh.setOnLoadmoreListener(new OnLoadmoreListener() {
//            @Override
//            public void onLoadmore(RefreshLayout refreshlayout) {
//                refreshlayout.getLayout().postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//                        pageNo++;
//                        userPresenter.getSystemMess(uid, type + "", pageNo + "", "10");
//                    }
//                }, 0);
//            }
//        });

        //设置头布局样式,全局有效
        refresh.setDefaultRefreshHeaderCreater(new DefaultRefreshHeaderCreater() {
            @Override
            public RefreshHeader createRefreshHeader(Context context, RefreshLayout layout) {
                //全局设置主题颜色
                layout.setPrimaryColorsId(R.color.colorPrimary, android.R.color.white);
                //指定为经典Header，默认是 贝塞尔雷达Header
                return new ClassicsHeader(context).setSpinnerStyle(SpinnerStyle.Translate);
            }
        });
        //设置脚布局样式,全局有效
        refresh.setDefaultRefreshFooterCreater(new DefaultRefreshFooterCreater() {
            @Override
            public RefreshFooter createRefreshFooter(Context context, RefreshLayout layout) {
                //指定为经典Footer，默认是 BallPulseFooter
                return new ClassicsFooter(context).setSpinnerStyle(SpinnerStyle.Translate);
            }
        });
        refresh.setRefreshHeader(new MaterialHeader(getActivity()).setShowBezierWave(true));
        //  refresh.setRefreshFooter(new BallPulseFooter(this).setSpinnerStyle(SpinnerStyle.Scale));
        refresh.finishLoadmore();
    }

   //头部视图
    public void titleShow(){
        if (uid.equals("")) {
            layout_unlogin.setVisibility(View.VISIBLE);
            layout_geren.setVisibility(View.GONE);
            layout_jingjiren.setVisibility(View.GONE);
        } else if (broker_validate.equals("0")||broker_validate.equals("2")){
            layout_geren.setVisibility(View.VISIBLE);
            layout_unlogin.setVisibility(View.GONE);
            layout_jingjiren.setVisibility(View.GONE);
        }else if (broker_validate.equals("1")){
            layout_geren.setVisibility(View.GONE);
            layout_unlogin.setVisibility(View.GONE);
            layout_jingjiren.setVisibility(View.VISIBLE);
        }
    }

    //
    public void isShowRedDot(){

        //接受附件单红点消息
        boolean fuJianOrder = (boolean) SPUtils.get(getActivity(),null,SPContants.FUJIAN_ORDER,false);
        if (fuJianOrder){ //我的签约的红点
//                home_img.setVisibility(View.VISIBLE);
            mySign_img.setVisibility(View.VISIBLE);
//                wode_img.setVisibility(View.VISIBLE);
        }else {
//                home_img.setVisibility(View.GONE);
            mySign_img.setVisibility(View.GONE);
//                wode_img.setVisibility(View.GONE);
        }

    }
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        setStatusBarHeight(v_statusbar);
        userPresenter = new UserPresenter(this);
        uid = SPUtils.get(getActivity(), null, SPContants.USER_ID, "") + "";
        broker_validate= SPUtils.get(getActivity(),null,SPContants.BrokerValidate,"")+"";
        titleShow();
        caozuo();
        //退出登录发送过来的广播
        IntentFilter filter1 = new IntentFilter(ActivityMyData.AVARTACTION);
        getActivity().registerReceiver(loginReceiver, filter1);
        //登录的广播
        IntentFilter filter2 = new IntentFilter("changeavart");
        getActivity().registerReceiver(loginReceiver, filter2);


    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            case R.id.person_shezhi:// 设置
                startActivity(new Intent(getActivity(), ActivitySetting.class));
                break;
            case R.id.layout_unlogin://没有登录
                startActivity(new Intent(getActivity(), LoginActivity.class));
                break;
            case R.id.lin_sign://签约
                LoginController.onMySignClick(getActivity(), null);
                break;
            case R.id.lin_rental:// 求租
                LoginController.onMyRental(getActivity(), null);
                break;
            case R.id.lin_collection:// 收藏
                LoginController.onMyCollectionClick(getActivity(), null);
                break;
            case R.id.lin_housekeeper:// 管家
                LoginController.onMyHousekeeper(getActivity(), null);
                break;
            case R.id.person_qiehuan:// 房源管理
                if ((SPUtils.get(getActivity(), null, SPContants.USER_ID, "") + "")
                        .equals("")) {
                    startActivity(new Intent(getActivity(), LoginActivity.class));
                } else {
                    if (!(SPUtils.get(getActivity(), null, SPContants.IdentityValidate, "") + "").equals("1")) {
                        showProgressDialog("正在获取信息", false);
                        userPresenter.getPersonData(uid);
                    } else {
                        startActivity(new Intent(getActivity(), ActivitySwitchRoles.class));
                    }
                }
                break;
            case R.id.lin_wallet:// 钱包
                if ((SPUtils.get(getActivity(), null, SPContants.USER_ID, "") + "")
                        .equals("")) {
                    intent = new Intent(getActivity(), LoginActivity.class);
                    startActivity(intent);
                } else {
                    if ((SPUtils.get(getActivity(), null,
                            SPContants.IdentityValidate, "") + "")// 未认证用户
                            .equals("0")
                            || (SPUtils.get(getActivity(), null,
                            SPContants.IdentityValidate, "") + "")// 未认证用户
                            .equals("")) {
                        ByAlert.alert("还没有实名认证哦!");
                    } else if ((SPUtils.get(getActivity(), null,
                            SPContants.IdentityValidate, "") + "")// 未认证用户
                            .equals("2")) {
                        ByAlert.alert("实名认证还在审核中哦!");
                    } else if ((SPUtils.get(getActivity(), null,
                            SPContants.WalletPass, "") + "")// 未设置支付密码用户
                            .equals("")) {//需先设置支付密码
                        intent = new Intent(getActivity(),
                                ActivityZhiFuPassSheZhi.class);
                        startActivity(intent);
                    } else if ((SPUtils.get(getActivity(), null,
                            SPContants.BrokerValidate, "") + "")// 为经纪人只能查看收支明细
                            .equals("1")) {
                        intent = new Intent(getActivity(), WebActivity.class);
                        intent.putExtra(
                                "url",
                                NetPublicConstant.WEB_URL
                                        + "/wallet/balance?uid=" + uid + "&psw=" + (SPUtils.get(getActivity(), null, SPContants.PASSWORD, "") + ""));
                        intent.putExtra("title", "收支明细");
                        startActivity(intent);
                    } else if ((SPUtils.get(getActivity(), null,
                            SPContants.IdentityValidate, "") + "")// 为房东可以查看自己的钱包
                            .equals("1")) {
                        intent = new Intent(getActivity(), ActivityMyWallte.class);
                        startActivity(intent);
                    }
                }
                break;
            case R.id.lin_detailed:// 明细
                if ((SPUtils.get(getActivity(), null, SPContants.USER_ID, "") + "")
                        .equals("")) {
                    intent = new Intent(getActivity(), LoginActivity.class);
                } else {
                    intent = new Intent(getActivity(), WebActivity.class);
                    intent.putExtra(
                            "url", NetPublicConstant.WEB_URL02
                                    + "/wallet/index?uid="
                                    + uid + "&psw=" + (SPUtils.get(getActivity(), null, SPContants.PASSWORD, "") + ""));
                    intent.putExtra("title", "资金交易明细");
                }
                startActivity(intent);
                break;

            case R.id.card_voucher: //我的卡券
                ByAlert.alert("待开发...");
//                startActivity(new Intent(getActivity(), ActivityMyIntgral.class));
                break;

            case R.id.exchangeLl: //兑换中心
                ByAlert.alert("待开发...");
//                startActivity(new Intent(getActivity(), ActivityExchangeMall.class));
                break;

            default:
                break;
        }
    }

    @Override
    public void update(Observable observable, Object data) {
        // TODO Auto-generated method stub
        ResultEntity entity = handlerError(data);
        if (entity != null) {
            if (entity.getEventType() == UserPresenter.wallet_success) {
                //结束加载
                refresh.finishRefresh();

                MyWalletBean myWalletBean = (MyWalletBean) entity.getData();
                if (myWalletBean != null) {
                    me_money.setContent(DoubleUtil.doubleTransform(myWalletBean.getBalance() + myWalletBean.getFinancial() + myWalletBean.getP2p() + ""));//余额 单位分
                    //   txt_zichan.setText("￥" + DoubleUtil.doubleTransform(myWalletBean.getBalance() + myWalletBean.getFinancial() + myWalletBean.getP2p() + ""));//余额 单位分
                    //  txt_shouyi.setText("￥" + DoubleUtil.doubleTransform(myWalletBean.getProfitHis()));//历史总收益,分, 当前为假数据

                }
            } else if (entity.getEventType() == UserPresenter.wallet_fail) {
                //结束加载
                refresh.finishRefresh();
            } else if (entity.getEventType() == UserPresenter.persondata_success) {
                PersonDataBean bean = (PersonDataBean) entity.getData();
                SavePersonData.saveData(getActivity(), bean);


                if (bean.getIdentityValidate().equals("2")) {
                    ByAlert.alert("实名认证还在审核中哦!");
                } else if (bean.getIdentityValidate().equals("1")) {
                    Intent intent = new Intent(getActivity(), ActivitySwitchRoles.class);
                    startActivity(intent);
                } else {
                    ByAlert.alert("还没有实名认证哦!");
                }
            } else if (entity.getEventType() == UserPresenter.persondata_fail) {
                ByAlert.alert(entity.getData() + "");
            } else if (entity.getEventType() == UserPresenter.agentCenter_success){//经纪人
                AgentCenterBean bean = (AgentCenterBean) entity.getData();
                //结束加载
                refresh.finishRefresh();

                me_qianyue_num.setContent(bean.getContract_count());
                me_qianyue_num1.setContent(bean.getVacancy_count());
                me_qianyue_num2.setContent(bean.getHouse_count());
                DecimalFormat df = new DecimalFormat("##0.00");

                String db = df.format( Double.parseDouble(bean.getRent_sum())/100);
                rentNumTv.setContent(db);
            } else if (entity.getEventType() == UserPresenter.agentCenter_fail){
                //结束加载
                refresh.finishRefresh();

            }
//            main_srl.setRefreshing(false);
        }
        try {
            closeProgressDialog();
        } catch (Exception e) {

        }
    }

    //是否显示红点
    public void updateRedDot(ImageView imageView,boolean isTrue){

        if (isTrue){
            imageView.setVisibility(View.VISIBLE);
        }else {
            imageView.setVisibility(View.GONE);
        }
    }

    public void updateBrakerValidate(){
        broker_validate= SPUtils.get(getActivity(),null,SPContants.BrokerValidate,"")+"";
        if (uid.equals("")) {
            layout_unlogin.setVisibility(View.VISIBLE);
            layout_geren.setVisibility(View.GONE);
        } else if (broker_validate.equals("0")||broker_validate.equals("2")){
            layout_geren.setVisibility(View.VISIBLE);
            layout_unlogin.setVisibility(View.GONE);
            layout_jingjiren.setVisibility(View.GONE);
            userPresenter.myWallet(uid);
        }else if (broker_validate.equals("1")){
            layout_geren.setVisibility(View.GONE);
            layout_unlogin.setVisibility(View.GONE);
            layout_jingjiren.setVisibility(View.VISIBLE);
            userPresenter.agentCenter(uid);
        }
    }

}
